// steeringwheel.cpp
#include "steeringwheel.h"
#include <QPainter>
#include <QGraphicsSceneMouseEvent>
#include <QtMath>
#include <QDebug>

SteeringWheel::SteeringWheel(QGraphicsItem *parent)
    : QGraphicsObject(parent)
{
    setFlag(ItemIsMovable, false);
    setFlag(ItemIsSelectable, true);
    setCacheMode(DeviceCoordinateCache);
}

QRectF SteeringWheel::boundingRect() const
{
    return QRectF(-100, -100, 200, 200);  // 方向盘大小
}

void SteeringWheel::paint(QPainter *painter,
                          const QStyleOptionGraphicsItem *,
                          QWidget *)
{
    painter->setRenderHint(QPainter::Antialiasing);

    // 绘制方向盘主体
    QRadialGradient grad(QPointF(0, 0), 90);
    grad.setColorAt(0, QColor(100, 100, 100));
    grad.setColorAt(1, QColor(50, 50, 50));
    painter->setBrush(grad);
    painter->setPen(QPen(Qt::black, 3));
    painter->drawEllipse(-80, -80, 160, 160);

    // 保存当前坐标系
    painter->save();

    // 旋转坐标系，使红十字与鼠标拖动方向一致
    painter->rotate(m_rotation);

    // 绘制红色十字
    painter->setPen(QPen(Qt::red, 5));
    painter->drawLine(0, -60, 0, 60);  // 垂直线
    painter->drawLine(-60, 0, 60, 0); // 水平线

    // 恢复坐标系
    painter->restore();
}

qreal SteeringWheel::rotation() const
{
    return m_rotation;
}

void SteeringWheel::setRotation(qreal newRotation)
{
    if (qFuzzyCompare(m_rotation, newRotation)) return;

    m_rotation = newRotation;
    update();  // 触发重绘
}

void SteeringWheel::setRotation1(qreal newRotation)
{
    if (qFuzzyCompare(m_rotation1, newRotation)) return;

    m_rotation1 = newRotation;

    //这里将角度发送出去
    emit rotationChanged(m_rotation1);  // 发射角度变化信号
}

void SteeringWheel::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        m_dragging = true;
        m_center = boundingRect().center();
        updateRotation(event->pos());
    }
    QGraphicsObject::mousePressEvent(event);
}

void SteeringWheel::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    if (m_dragging) {
        updateRotation(event->pos());
    }
    QGraphicsObject::mouseMoveEvent(event);
}

void SteeringWheel::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        m_dragging = false;
        setRotation(0);  // 松开鼠标时复位
        setRotation1(0);  // 松开鼠标时复位
    }
    QGraphicsObject::mouseReleaseEvent(event);
}

void SteeringWheel::updateRotation(const QPointF &mousePos)
{
    QPointF delta = mousePos - m_center;

    // 计算角度（默认零度在右侧，顺时针增加）
    qreal angle = qRadiansToDegrees(qAtan2(delta.y(), delta.x()));

    // 调整红十字的旋转，跟随鼠标
    angle = angle - 90;  // 上方为 0 度，下方为 180 度

    // 确保角度在 0 到 360 度之间
    if (angle < -180) angle += 360;
    if (angle > 180) angle -= 360;

    setRotation(angle);
    setRotation1(angle);
}
